<template>
  <div class="space-y-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">
      <div class="card lg:col-span-2">
        <div class="flex items-center gap-4">
          <img 
            v-if="userStore.currentBaby?.avatarUrl && !avatarLoadError" 
            class="w-16 h-16 rounded-full object-cover" 
            :src="userStore.currentBaby.avatarUrl" 
            alt="baby" 
            @error="handleAvatarError"
          />
          <DefaultAvatar v-else :name="babyNickname" />
          <div class="flex-1">
            <div class="flex items-center gap-2">
              <div class="text-xl font-semibold">{{ babyNickname }}</div>
              <div v-if="userStore.familyBabies.length > 1" class="flex items-center gap-2">
                <select v-model="userStore.currentBabyId" @change="switchBaby" class="text-sm border rounded px-2 py-1">
                  <option v-for="baby in userStore.familyBabies" :key="baby.id" :value="baby.id">{{ baby.nickname }}</option>
                </select>
                <RouterLink to="/settings" class="text-xs text-secondary">管理宝宝</RouterLink>
              </div>
              <div v-else-if="userStore.familyBabies.length === 0" class="text-sm text-gray-500">
                <RouterLink to="/settings" class="text-secondary">添加宝宝档案</RouterLink>
              </div>
            </div>
            <div class="text-gray-500 text-sm">今日月龄：{{ babyAge }}</div>
          </div>
        </div>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 mt-4 text-sm">
          <div class="p-3 rounded bg-bg">上次喂奶：{{ lastFeeding }}</div>
          <div class="p-3 rounded bg-bg">上次换尿布：{{ lastDiaper }}</div>
          <div class="p-3 rounded bg-bg">睡眠状态：{{ sleepState }}</div>
          <div class="p-3 rounded bg-bg">今日总奶：{{ todayFormulaMl }} ml / 母乳 {{ todayBreastMinutes }} 分</div>
        </div>
      </div>
      <div class="card">
        <div class="font-semibold mb-2">快速操作</div>
        <div class="grid grid-cols-2 gap-2">
          <button class="btn-primary text-sm py-2" @click="openFeeding">喂奶记录</button>
          <button class="btn-primary text-sm py-2" @click="openDiaper">换尿布</button>
          <button class="btn-primary text-sm py-2" @click="openSleep">睡觉/醒来</button>
          <button class="btn-primary text-sm py-2" @click="openCry">哭闹记录</button>
        </div>
      </div>
    </div>

    <div class="card">
      <div class="flex justify-between items-center mb-3">
        <div class="font-semibold">今日动态</div>
        <RouterLink to="/timeline" class="text-secondary">查看全部</RouterLink>
      </div>
      <div v-if="loadingTimeline" class="text-sm text-gray-500">加载中...</div>
      <ul v-else class="space-y-3 text-sm">
        <li v-if="timeline.length===0" class="p-4 rounded-lg bg-gray-50 text-gray-500 text-center">
          <div class="text-gray-400 mb-1">📝</div>
          <div>暂无记录</div>
        </li>
        <li v-for="item in timeline" :key="item.key" class="group relative p-4 rounded-lg bg-white border border-gray-100 hover:border-gray-200 hover:shadow-sm transition-all duration-200">
          <!-- 记录内容区域 -->
          <div class="flex items-start gap-3">
            <!-- 时间标签 -->
            <div class="flex-shrink-0">
              <div class="text-xs font-medium text-gray-500 bg-gray-100 px-2 py-1 rounded-full">
                {{ item.time }}
              </div>
            </div>
            
            <!-- 主要内容 -->
            <div class="flex-1 min-w-0">
              <!-- 类型标签和内容 -->
              <div class="flex items-center gap-2 mb-1">
                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium" 
                      :class="getTypeBadgeClass(item.type)">
                  {{ getTypeIcon(item.type) }} {{ item.typeText }}
                </span>
              </div>
              <div class="text-gray-700 text-sm leading-relaxed">{{ item.content }}</div>
            </div>
            
            <!-- 操作按钮区域 -->
            <div class="flex-shrink-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
              <div class="flex gap-1">
                <button 
                  class="p-1.5 text-gray-400 hover:text-blue-500 hover:bg-blue-50 rounded-md transition-colors duration-200"
                  @click="editRecord(item)"
                  title="编辑记录"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                  </svg>
                </button>
                <button 
                  class="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-md transition-colors duration-200"
                  @click="deleteRecord(item)"
                  title="删除记录"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                  </svg>
                </button>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>

  <!-- 模态框 -->
  <FeedingModal v-model:open="modals.feeding" :edit-data="editData" @saved="onRecordSaved" />
  <DiaperModal v-model:open="modals.diaper" :edit-data="editData" @saved="onRecordSaved" />
  <SleepModal v-model:open="modals.sleep" :edit-data="editData" @saved="onRecordSaved" />
  <CryModal v-model:open="modals.cry" :edit-data="editData" @saved="onRecordSaved" />
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { RouterLink, useRouter } from 'vue-router';
import FeedingModal from '../widgets/FeedingModal.vue';
import DiaperModal from '../widgets/DiaperModal.vue';
import SleepModal from '../widgets/SleepModal.vue';
import CryModal from '../widgets/CryModal.vue';
import DefaultAvatar from '../components/DefaultAvatar.vue';
import { useUserStore } from '../stores/user';
import { type RecordsByDatePayload, type TimelineByDatePayload, API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function getFamilyBabies(familyId: number) {
  const token = localStorage.getItem('auth_token');
  console.log('Dashboard getFamilyBabies - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/family/${familyId}/babies`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    }
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function recordsByDate(payload: RecordsByDatePayload) {
  const token = localStorage.getItem('auth_token');
  console.log('Dashboard recordsByDate - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/by-date`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function timelineByDate(payload: TimelineByDatePayload) {
  const token = localStorage.getItem('auth_token');
  console.log('Dashboard timelineByDate - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/timeline/by-date`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const modals = reactive({ feeding: false, diaper: false, sleep: false, cry: false });
const editData = ref<any>(null);

const openFeeding = () => {
  editData.value = null;
  modals.feeding = true;
};
const openDiaper = () => {
  editData.value = null;
  modals.diaper = true;
};
const openSleep = () => {
  editData.value = null;
  modals.sleep = true;
};
const openCry = () => {
  editData.value = null;
  modals.cry = true;
};

// 记录保存完成后的处理
function onRecordSaved() {
  console.log('记录已保存，刷新首页数据');
  // 重新加载概览数据和时光轴数据
  loadOverview();
  loadTimeline();
}

// 编辑记录
function editRecord(item: any) {
  console.log('编辑记录:', item);
  editData.value = item.rawData; // 保存原始数据用于编辑
  
  // 根据记录类型打开对应的模态框
  switch (item.type) {
    case 'FEEDING':
      modals.feeding = true;
      break;
    case 'DIAPER':
      modals.diaper = true;
      break;
    case 'SLEEP':
      modals.sleep = true;
      break;
    case 'CRY':
      modals.cry = true;
      break;
  }
}

// 删除记录
async function deleteRecord(item: any) {
  if (!confirm('确定要删除这条记录吗？')) {
    return;
  }
  
  try {
    const token = localStorage.getItem('auth_token');
    const recordType = item.type.toLowerCase();
    const recordId = item.rawData.id;
    
    const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/${recordType}/${recordId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token || ''}`
      }
    });
    
    if (!resp.ok) {
      const errorText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errorText}`);
    }
    
    // 删除成功后刷新数据
    loadOverview();
    loadTimeline();
  } catch (error) {
    console.error('删除记录失败:', error);
    alert('删除失败，请重试');
  }
}

// 头像加载错误处理
const avatarLoadError = ref(false);

function handleAvatarError() {
  console.log('头像加载失败，切换到默认头像');
  avatarLoadError.value = true;
}

const lastFeeding = ref<string>('--');
const lastDiaper = ref<string>('--');
const sleepState = ref<string>('--');
const todayDate = new Date().toLocaleDateString('en-CA');
const todayFormulaMl = ref<number>(0);
const todayBreastMinutes = ref<number>(0);
const timeline = ref<any[]>([]);
const loadingTimeline = ref(false);

// 使用全局状态
const userStore = useUserStore();
const router = useRouter();

// 计算属性
const babyNickname = computed(() => userStore.currentBaby?.nickname || '糖宝宝');
const babyAge = computed(() => {
  if (!userStore.currentBaby?.birthday) return '5月23天';
  const birth = new Date(userStore.currentBaby.birthday);
  const now = new Date();
  const diffTime = now.getTime() - birth.getTime();
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
  const months = Math.floor(diffDays / 30);
  const days = diffDays % 30;
  return `${months}月${days}天`;
});

function formatTime(iso: string) {
  const d = new Date(iso);
  return d.toTimeString().slice(0, 5);
}

async function loadOverview() {
  if (!userStore.currentBabyId) return;
  const payload: RecordsByDatePayload = { babyId: userStore.currentBabyId, date: todayDate };
  const data = await recordsByDate(payload);
  if (data.feedings?.length) {
    const f = data.feedings.sort((a: any, b: any) => b.eventTime.localeCompare(a.eventTime))[0];
    lastFeeding.value = f.feedingType === 'FORMULA'
      ? `${formatTime(f.eventTime)} / ${f.formulaMl ?? '-'}ml`
      : `${formatTime(f.eventTime)} / 左${f.leftMinutes ?? 0}分 右${f.rightMinutes ?? 0}分`;
  } else lastFeeding.value = '--';

  if (data.diapers?.length) {
    const d = data.diapers.sort((a: any, b: any) => b.eventTime.localeCompare(a.eventTime))[0];
    lastDiaper.value = `${formatTime(d.eventTime)}`;
  } else lastDiaper.value = '--';

  if (data.sleeps?.length) {
    const ongoing = data.sleeps.find((s: any) => !s.sleepEnd);
    sleepState.value = ongoing ? '睡觉中' : '清醒';
  } else sleepState.value = '清醒';

  todayFormulaMl.value = data.feedings
    ?.filter((f: any) => f.feedingType === 'FORMULA')
    .reduce((sum: number, f: any) => sum + (f.formulaMl || 0), 0) || 0;

  todayBreastMinutes.value = data.feedings
    ?.filter((f: any) => f.feedingType === 'BREAST_MILK')
    .reduce((sum: number, f: any) => sum + (f.leftMinutes || 0) + (f.rightMinutes || 0), 0) || 0;
}

async function loadTimeline() {
  if (!userStore.currentBabyId) return;
  try {
    loadingTimeline.value = true;
    const payload: TimelineByDatePayload = { babyId: userStore.currentBabyId, date: todayDate };
    const res = await timelineByDate(payload);
    const rawItems = Array.isArray(res) ? res : [];
    
    // 处理时光轴数据，转换为首页显示格式
    timeline.value = rawItems.map((item: any, idx: number) => {
      return {
        key: `${item.type}-${idx}-${item.eventTime}`,
        time: formatTime(item.eventTime),
        typeText: mapTypeText(item.type),
        content: summarizeTimelineItem(item),
        type: item.type,
        rawData: item.data // 保存原始数据用于编辑
      };
    });
  } finally {
    loadingTimeline.value = false;
  }
}

function mapTypeText(type: string) {
  switch (type) {
    case 'FEEDING': return '喂奶';
    case 'DIAPER': return '尿布';
    case 'SLEEP': return '睡眠';
    case 'CRY': return '哭闹';
    default: return type;
  }
}

// 获取类型图标
function getTypeIcon(type: string) {
  switch (type) {
    case 'FEEDING': return '🍼';
    case 'DIAPER': return '👶';
    case 'SLEEP': return '😴';
    case 'CRY': return '😢';
    default: return '📝';
  }
}

// 获取类型标签样式
function getTypeBadgeClass(type: string) {
  switch (type) {
    case 'FEEDING': return 'bg-blue-100 text-blue-700 border border-blue-200';
    case 'DIAPER': return 'bg-green-100 text-green-700 border border-green-200';
    case 'SLEEP': return 'bg-purple-100 text-purple-700 border border-purple-200';
    case 'CRY': return 'bg-orange-100 text-orange-700 border border-orange-200';
    default: return 'bg-gray-100 text-gray-700 border border-gray-200';
  }
}

function summarizeTimelineItem(item: any) {
  if (item.type === 'FEEDING') {
    const d = item.data;
    return d.feedingType === 'FORMULA'
      ? `配方奶 ${d.formulaMl ?? '-'} ml`
      : `母乳 左${d.leftMinutes ?? 0}分 右${d.rightMinutes ?? 0}分`;
  }
  if (item.type === 'DIAPER') {
    const d = item.data;
    return d.diaperType === 'WET' ? '清尿' : d.diaperType === 'DIRTY' ? '便便' : '混合';
  }
  if (item.type === 'SLEEP') {
    const d = item.data;
    const start = formatTime(d.sleepStart);
    const end = d.sleepEnd ? formatTime(d.sleepEnd) : '至今';
    return `睡眠 ${start} - ${end}`;
  }
  if (item.type === 'CRY') {
    const d = item.data;
    return `哭闹 ${formatTime(d.startTime)}${d.endTime ? ' - ' + formatTime(d.endTime) : ''}`;
  }
  return '';
}

async function loadBabyProfile() {
  if (!userStore.currentUser?.familyId) {
    console.log('用户未登录或家庭ID不存在，跳转到登录页');
    router.push('/login');
    return;
  }

  try {
    console.log('正在加载宝宝档案...', userStore.currentUser.familyId);
    const babies = await getFamilyBabies(userStore.currentUser.familyId);
    console.log('所有宝宝:', babies);
    
    userStore.setFamilyBabies(babies || []);
    
    if (userStore.familyBabies.length > 0) {
      // 切换宝宝后重新加载数据
      loadOverview();
      loadTimeline();
    } else {
      console.log('未找到宝宝档案，请先去设置页面创建宝宝档案');
    }
  } catch (error) {
    console.error('加载宝宝档案失败:', error);
  }
}

function switchBaby() {
  if (userStore.currentBabyId) {
    console.log('切换到宝宝:', userStore.currentBaby);
    // 重置头像错误状态，允许重新尝试加载新宝宝的头像
    avatarLoadError.value = false;
    // 切换宝宝后重新加载数据
    loadOverview();
    loadTimeline();
  }
}

// 监听宝宝切换，重置头像错误状态
watch(() => userStore.currentBabyId, () => {
  avatarLoadError.value = false;
});

onMounted(() => { 
  console.log('Dashboard mounted, 用户状态:', userStore.currentUser);
  console.log('是否已登录:', userStore.isLoggedIn);
  
  // 如果没有登录，立即跳转
  if (!userStore.isLoggedIn) {
    console.log('检测到未登录，立即跳转到登录页');
    router.push('/login');
    return;
  }
  
  loadBabyProfile(); 
});
</script>

<style scoped></style>